package com.windoent.yugioh.ui.activity.saishi;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.text.Html;
import android.util.TypedValue;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.widget.LinearLayout;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.baidu.mobstat.StatService;
import com.windoent.yugioh.MyApplication;
import com.windoent.yugioh.R;
import com.windoent.yugioh.adapter.GameManagerFragmentViewPagerAdapter;
import com.windoent.yugioh.base.BaseActivity;
import com.windoent.yugioh.bean.GameStatusRoleBean;
import com.windoent.yugioh.bean.eventbus.FragmentActivityMessageEvent;
import com.windoent.yugioh.constants.Constants;
import com.windoent.yugioh.http.PhoneLive;
import com.windoent.yugioh.ui.activity.meinfo.MyMsgActivity;
import com.windoent.yugioh.ui.fragment.saishi.baoming.BaoMingAuthCaiPanFragment;
import com.windoent.yugioh.ui.fragment.saishi.baoming.BaoMingAuthXuanShouFragment;
import com.windoent.yugioh.ui.fragment.saishi.baoming.BaoMingCaiPanFragment;
import com.windoent.yugioh.ui.fragment.saishi.baoming.BaoMingDetailsFragment;
import com.windoent.yugioh.ui.fragment.saishi.end.EndedDetailsFragment;
import com.windoent.yugioh.ui.fragment.saishi.end.EndedDuiZhenFragment;
import com.windoent.yugioh.ui.fragment.saishi.end.EndedPanFaFragment;
import com.windoent.yugioh.ui.fragment.saishi.end.EndedRuiShiLunFragment;
import com.windoent.yugioh.ui.fragment.saishi.end.EndedSaiGuoFragment;
import com.windoent.yugioh.ui.fragment.saishi.ongoing.OnGoingDetailsFragment;
import com.windoent.yugioh.ui.fragment.saishi.ongoing.OnGoingDuiZhenFragment;
import com.windoent.yugioh.ui.fragment.saishi.ongoing.OnGoingPanFaFragment;
import com.windoent.yugioh.ui.fragment.saishi.ongoing.OnGoingRuiShiLunFragment;
import com.windoent.yugioh.ui.fragment.saishi.ongoing.OnGoingSaiGuoFragment;
import com.windoent.yugioh.ui.fragment.saishi.ongoing.OnGoingShenHeFragment;
import com.windoent.yugioh.utils.BaseMethod;
import com.windoent.yugioh.utils.BaseUtils;
import com.windoent.yugioh.utils.LogUtils;
import com.windoent.yugioh.utils.TDevice;
import com.windoent.yugioh.utils.ToastUtils;
import com.windoent.yugioh.widget.ActivityTitle;
import com.windoent.yugioh.widget.MessageItem;
import com.windoent.yugioh.widget.ScaleTransitionPagerTitleView;
import com.windoent.yugioh.widget.dialog.ShareQqWechatDialog;
import com.zhy.http.okhttp.callback.StringCallback;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.onekeyshare.OnekeyShare;
import okhttp3.Call;

/**
 * author : robert
 * date   : 2021/5/17 13:47
 * desc   :赛事
 */
public class GameActivity extends BaseActivity {
    private ActivityTitle mActivityTitle;
    private LinearLayout mLlShare;
    private MessageItem mItemMessage;
    private MagicIndicator mMagicIndicator;
    private ViewPager mViewpager;

    private List<String> fragmentsTitle = new ArrayList<>();
    private List<Fragment> fragments = new ArrayList<>();
    private GameManagerFragmentViewPagerAdapter pagerAdapter;
    private CommonNavigator commonNavigator;
    private String id = "";
    private String rule;

    @Override
    public int getLayout() {
        return R.layout.activity_saishi_baoming_ing;
    }

    @Override
    public void initView() {
        super.initView();
        mActivityTitle = (ActivityTitle) findViewById(R.id.activity_title);
        immersiveStatusBar(mActivityTitle.getView());
        mLlShare = (LinearLayout) findViewById(R.id.ll_share);
        mItemMessage = (MessageItem) findViewById(R.id.item_message);
        mMagicIndicator = (MagicIndicator) findViewById(R.id.magicIndicator);
        mViewpager = (ViewPager) findViewById(R.id.viewpager);

    }

    //接收粘性消息
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(FragmentActivityMessageEvent event) {
        int message = event.getMessage();
        String role = event.getRole();
        int statusId = event.getStatusId();
        if (message == 1) {
            if (statusId == 8) {
                magicEnd(role);
            } else if (statusId == 2) {
                //报名中
                getDetailsSaiShiData(id, role);
            } else {
                //进行中
                magicStatus(role);
            }
        }
    }

    //获取赛事状态角色
    private void getGameStatusRole(String id) {
        PhoneLive.getGameStatusRole(getUserToken(), id, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                ToastUtils.showText(e.getMessage());
            }

            @Override
            public void onResponse(String response, int idres) {
                if (BaseUtils.isJSONValid(response)) {
                    try {
                        if (BaseUtils.codeIs0(mContext, response)) {
                            GameStatusRoleBean json = gson.fromJson(response, GameStatusRoleBean.class);
                            if (json != null) {
                                GameStatusRoleBean.DataBean data = json.getData();
                                if (data != null) {
                                    String role = data.getRole();
                                    int statusid = data.getStatusid();
                                    if (statusid == 8) {
                                        magicEnd(role);
                                    } else if (statusid == 2) {
                                        //报名中
                                        getDetailsSaiShiData(id, role);
                                    } else {
                                        //进行中
                                        magicStatus(role);
                                    }
                                }
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    ToastUtils.showText(getString(R.string.string_response_error));
                }
            }
        });
    }

    @Override
    public void initData() {
        super.initData();
        EventBus.getDefault().register(mContext);
        Intent intent = getIntent();
        id = intent.getStringExtra("id");
        rule = intent.getStringExtra("rule");
        getGameStatusRole(id);
    }

    //详情（报名中）
    private void getDetailsSaiShiData(String id, String role) {
        PhoneLive.getDetailsSaiShiData(getUserToken(), id, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                ToastUtils.showText(e.getMessage());
            }

            @Override
            public void onResponse(String response, int id) {
                //magic设置（报名中）
                magic(response, role);
            }
        });
    }

    @Override
    public void initListener() {
        super.initListener();
        mActivityTitle.setBackListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        mItemMessage.setListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(mContext, MyMsgActivity.class));
            }
        });
        mLlShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                shareQQWechatDialog();
            }
        });
    }

    //分享dialog
    private void shareQQWechatDialog() {
        ShareQqWechatDialog dialog = new ShareQqWechatDialog(mContext);
        dialog.setOnclickListener(new ShareQqWechatDialog.onOnclickListener() {
            @Override
            public void onClick(String name) {
                shareQQWechat(name);
            }
        });
        dialog.show();
    }

    //分享
    private void shareQQWechat(String platform) {
        OnekeyShare oks = new OnekeyShare(); //关闭sso授权 oks.disableSSOWhenAuthorize();
        //指定分享的平台，如果为空，还是会调用九宫格的平台列表界面
        if (platform != null) {
            oks.setPlatform(platform);
        }
        // title标题，微信、QQ和QQ空间等平台使用
        oks.setTitle(getString(R.string.string_share_word));
        // titleUrl QQ和QQ空间跳转链接
        oks.setTitleUrl(Constants.testWebUrl);
        // text是分享文本，所有平台都需要这个字段
        oks.setText(getString(R.string.string_add_address_warning));
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
//        oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
        oks.setImageUrl("http://47.101.31.182/group1/M00/00/02/rBM8DV8ebh-ARJuGAABck3rGBcs906.png");
        // url在微信、微博，Facebook等平台中使用
        oks.setUrl(Constants.testWebUrl);
        //QQ空间
        oks.setSite(getString(R.string.app_name));
        oks.setCallback(new PlatformActionListener() {
            @Override
            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                ToastUtils.showText(getString(R.string.string_share_sucess));
                LogUtils.d("ShareLogin", "onComplete ---->  分享成功");
            }

            @Override
            public void onError(Platform platform, int i, Throwable throwable) {
                LogUtils.d("ShareLogin", "onError ---->  失败" + throwable.getStackTrace());
                LogUtils.d("ShareLogin", "onError ---->  失败" + throwable.getMessage());
                LogUtils.d("ShareSDK", "onError ---->  取消分享" + throwable.toString());
                throwable.printStackTrace();
                ToastUtils.showText(getString(R.string.string_share_fail));
            }

            @Override
            public void onCancel(Platform platform, int i) {
                LogUtils.d("ShareLogin", "onCancel ---->  分享取消");
            }
        });
        // 启动分享GUI
        oks.show(this);
    }

    //报名中
    private void magic(String response, String role) {
        getInitData(response, role);
        setMagicIndicator();
        if (pagerAdapter == null) {
            pagerAdapter = new GameManagerFragmentViewPagerAdapter(getSupportFragmentManager(), FragmentStatePagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT, mContext, fragmentsTitle, fragments);
            if (mViewpager != null)
                //The application's PagerAdapter changed the adapter's contents without calling PagerAdapter
                if (mViewpager.getAdapter() != null) {
                    pagerAdapter.notifyDataSetChanged();
                } else
                    mViewpager.setAdapter(pagerAdapter);
        } else {
            pagerAdapter.notifyDataSetChanged();
        }
    }

    //已结束
    private void magicEnd(String role) {
        getInitEndData(role);
        setMagicIndicator();
        if (pagerAdapter == null) {
            pagerAdapter = new GameManagerFragmentViewPagerAdapter(getSupportFragmentManager(), FragmentStatePagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT, mContext, fragmentsTitle, fragments);
            if (mViewpager != null)
                //The application's PagerAdapter changed the adapter's contents without calling PagerAdapter
                if (mViewpager.getAdapter() != null) {
                    pagerAdapter.notifyDataSetChanged();
                } else {
                    mViewpager.setAdapter(pagerAdapter);
                }
        } else {
            pagerAdapter.notifyDataSetChanged();
        }
    }

    //已结束
    private void getInitEndData(String role) {
        if (fragmentsTitle != null) {
            fragmentsTitle.clear();
            fragmentsTitle.add(getString(R.string.string_details));
            fragmentsTitle.add(getString(R.string.string_duizhen));
            if (BaseMethod.isNull(rule) || !rule.equals("2"))
                fragmentsTitle.add(getString(R.string.string_ruishilun_rank));
            fragmentsTitle.add(getString(R.string.string_panfa));
            fragmentsTitle.add(getString(R.string.string_game_result));
        }
        if (fragments != null) {
            fragments.clear();
            fragments.add(EndedDetailsFragment.newsInstance(id));
            fragments.add(EndedDuiZhenFragment.newsInstance(id));
            if (BaseMethod.isNull(rule) || !rule.equals("2"))
                fragments.add(EndedRuiShiLunFragment.newsInstance(id));
            fragments.add(EndedPanFaFragment.newsInstance(id));
            fragments.add(EndedSaiGuoFragment.newsInstance(id));
        }
    }

    //进行中
    private void magicStatus(String role) {
        getInitStatusData(role);
        setMagicIndicator();
        if (pagerAdapter == null) {
            pagerAdapter = new GameManagerFragmentViewPagerAdapter(getSupportFragmentManager(), FragmentStatePagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT, mContext, fragmentsTitle, fragments);
            if (mViewpager != null)
                //The application's PagerAdapter changed the adapter's contents without calling PagerAdapter
                if (mViewpager.getAdapter() != null) {
                    pagerAdapter.notifyDataSetChanged();
                } else {
                    mViewpager.setAdapter(pagerAdapter);
                }
        } else {
            pagerAdapter.notifyDataSetChanged();
        }
    }

    //进行中
    private void getInitStatusData(String role) {
        boolean notJoin = BaseMethod.notNull(role) && role.equals("notJoin");
        boolean pReferee = BaseMethod.notNull(role) && role.equals("pReferee");
        boolean player = BaseMethod.notNull(role) && role.equals("player");
        boolean referee = BaseMethod.notNull(role) && role.equals("referee");
        boolean customer = BaseMethod.notNull(role) && role.equals("customer");
        boolean customerReferee = BaseMethod.notNull(role) && role.equals("customerReferee");
        boolean pending = BaseMethod.notNull(role) && role.equals("pending");
        if (fragmentsTitle != null) {
            fragmentsTitle.clear();
            fragmentsTitle.add(getString(R.string.string_details));
            fragmentsTitle.add(getString(R.string.string_duizhen));
            if (pReferee || referee || customerReferee)
                fragmentsTitle.add(getString(R.string.string_shehe));
            if (BaseMethod.isNull(rule) || !rule.equals("2"))
                fragmentsTitle.add(getString(R.string.string_ruishilun_rank));
            fragmentsTitle.add(getString(R.string.string_panfa));
            fragmentsTitle.add(getString(R.string.string_game_result));
        }
        if (fragments != null) {
            fragments.clear();
            fragments.add(OnGoingDetailsFragment.newsInstance(id));
            fragments.add(OnGoingDuiZhenFragment.newsInstance(id));
            if (pReferee || referee || customerReferee)
                fragments.add(OnGoingShenHeFragment.newsInstance(id));
            if (BaseMethod.isNull(rule) || !rule.equals("2"))
                fragments.add(OnGoingRuiShiLunFragment.newsInstance(id));
            fragments.add(OnGoingPanFaFragment.newsInstance(id));
            fragments.add(OnGoingSaiGuoFragment.newsInstance(id));
        }
    }

    /**
     * "customer":"商家",
     * "customerReferee":"商家+主裁判",
     * "notJoin":"没有参加",
     * "pReferee":"主裁判",
     * "player":"选手",
     * "referee":"裁判",
     * "visitor":"游客"
     * "pending":"角色正在审核中"
     */
    //报名中
    private void getInitData(String response, String role) {
        boolean notJoin = BaseMethod.notNull(role) && role.equals("notJoin");
        boolean pReferee = BaseMethod.notNull(role) && role.equals("pReferee");
        boolean player = BaseMethod.notNull(role) && role.equals("player");
        boolean referee = BaseMethod.notNull(role) && role.equals("referee");
        boolean customer = BaseMethod.notNull(role) && role.equals("customer");
        boolean customerReferee = BaseMethod.notNull(role) && role.equals("customerReferee");
        boolean pending = BaseMethod.notNull(role) && role.equals("pending");
        if (fragmentsTitle != null) {
            fragmentsTitle.clear();
            fragmentsTitle.add(getString(R.string.string_details));
            if (notJoin || pReferee || player || referee || pending) {
                fragmentsTitle.add(getString(R.string.string_role_caipan));
            }
            if (customer || customerReferee) {
                fragmentsTitle.add(getString(R.string.string_auth_xuanshou));
                fragmentsTitle.add(getString(R.string.string_auth_caipan));
            }
        }
        if (fragments != null) {
            fragments.clear();
            fragments.add(BaoMingDetailsFragment.newsInstance(id, response));
            if (notJoin || pReferee || player || referee || pending)
                fragments.add(BaoMingCaiPanFragment.newsInstance(id, response));
            if (customer || customerReferee) {
                fragments.add(BaoMingAuthXuanShouFragment.newsInstance(id, response));
                fragments.add(BaoMingAuthCaiPanFragment.newsInstance(id, response));
            }
        }
    }

    private void setMagicIndicator() {
        if (commonNavigator == null) {
            commonNavigator = new CommonNavigator(mContext);
            CommonNavigatorAdapter adapterNavigstor = new CommonNavigatorAdapter() {
                @Override
                public int getCount() {
                    return fragmentsTitle == null ? 0 : fragmentsTitle.size();
                }

                @Override
                public IPagerTitleView getTitleView(Context context, int index) {
                    ScaleTransitionPagerTitleView titleView = new ScaleTransitionPagerTitleView(mContext);
                    titleView.setText(Html.fromHtml(fragmentsTitle.get(index)));
                    titleView.setNormalColor(Color.parseColor("#FFCCCCCC"));
                    titleView.setSelectedColor(Color.WHITE);
                    titleView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20f);
                    titleView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            mViewpager.setCurrentItem(index, false);
                        }
                    });
                    return titleView;
                }

                @Override
                public IPagerIndicator getIndicator(Context context) {
                    LinePagerIndicator indicator = new LinePagerIndicator(mContext);
                    indicator.setMode(LinePagerIndicator.MODE_EXACTLY);
                    indicator.setLineHeight(TDevice.dp2px(mContext, 5));
                    indicator.setLineWidth(TDevice.dp2px(mContext, 30));
                    indicator.setRoundRadius(TDevice.dp2px(mContext, 6));
                    indicator.setStartInterpolator(new AccelerateInterpolator());
                    indicator.setEndInterpolator(new DecelerateInterpolator(2.0f));
                    indicator.setColors(Color.parseColor("#FFEC4E4E"));
                    return indicator;
                }
            };
            commonNavigator.setAdapter(adapterNavigstor);

            if (mMagicIndicator != null)
                mMagicIndicator.setNavigator(commonNavigator);
            if (mMagicIndicator != null && mViewpager != null)
                ViewPagerHelper.bind(mMagicIndicator, mViewpager);
        } else {
            commonNavigator.notifyDataSetChanged();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        StatService.onPageStart(this, "赛事报名中界面");
        if (mItemMessage != null) {
            mItemMessage.setTvTitle(MyApplication.getInstance().getMsgNumber());
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        StatService.onPageEnd(this, "赛事报名中界面");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //解除注册EventBus
        EventBus.getDefault().unregister(this);
    }
}
